const schedule = require("node-schedule");
const util = require("./../util/util");
const model = require("./../model");
const redis = require("./../redis");
const config = require("./../config");

// 全局
global.BaaS = {};

// 每天0:00计划任务
// 0 0 * * *
const job = schedule.scheduleJob("0 0 * * *", async () => {
  // 建立连接
  const mysql = model.getModels(config.mysql);

  // 全局
  BaaS.bookshelf = mysql.bookshelf;
  BaaS.Models = mysql.Models;
  BaaS.redis = redis;

  console.log("Redis请求日志开始处理");
  const requestLogs = [];
  const requestLength = await BaaS.redis.llenAsync(
    util.getVersionKey("baas_log_request")
  );
  for (let i = 0; i < requestLength; i++) {
    const requestLog = await BaaS.redis.lpopAsync(
      util.getVersionKey("baas_log_request")
    );
    requestLogs.push(JSON.parse(requestLog));
  }

  await BaaS.bookshelf.Collection.extend({
    model: BaaS.Models.log.request
  })
    .forge(requestLogs)
    .invokeThen("save");
  console.log("Redis请求日志结束处理");

  console.log("Redis调试日志开始处理");
  const debugLogs = [];
  const debugLength = await BaaS.redis.llenAsync(
    util.getVersionKey("baas_log_debug")
  );
  for (let i = 0; i < debugLength; i++) {
    const debugLog = await BaaS.redis.lpopAsync(
      util.getVersionKey("baas_log_debug")
    );
    debugLogs.push(JSON.parse(debugLog));
  }

  await BaaS.bookshelf.Collection.extend({
    model: BaaS.Models.log.debug
  })
    .forge(debugLogs)
    .invokeThen("save");
  console.log("Redis调试日志结束处理");

  console.log("Redis短信验证码日志开始处理");
  const smsLogs = [];
  const smsLength = await BaaS.redis.llenAsync(
    util.getVersionKey("baas_log_sms")
  );
  for (let i = 0; i < smsLength; i++) {
    const smsLog = await BaaS.redis.lpopAsync(
      util.getVersionKey("baas_log_sms")
    );
    smsLogs.push(JSON.parse(smsLog));
  }

  await BaaS.bookshelf.Collection.extend({
    model: BaaS.Models.log.sms
  })
    .forge(smsLogs)
    .invokeThen("save");
  console.log("Redis短信验证码日志结束处理");

  // 定时处理redis缓存，有效期是-1的值，删除

  // 断开连接
  BaaS.bookshelf.knex.destroy();
});
